package com.huatai.datadevelop.websocket;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author hecai
 * @description: TODO
 * @date 2023/2/13 14:36
 * @Version 1.0
 */
@Slf4j
@Component
@ServerEndpoint(value = "/webSocket/timing/table/{interfaceName}")
public class TimingTableWebSocket {

    /**
     * 存放所有在线的客户端
     */
    public static Map<String, Session> clients = new ConcurrentHashMap<>();
    public static Map<String, Session> sendMessageClients = new ConcurrentHashMap<>();

    private String interfaceName = "";
    public String getInterfaceName(){
        return interfaceName;
    }

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session,@PathParam("interfaceName")String interfaceName) {
        Integer integer = pageAnd.addNumber();
        clients.put(interfaceName+session.getId(), session);
        log.info("有新连接加入："+ interfaceName +session.getId()+"，当前在线人数为："+integer);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session,@PathParam("interfaceName")String interfaceName) {
        Integer integer = pageAnd.decrement();
        clients.remove(interfaceName+session.getId());
        sendMessageClients.remove(interfaceName+session.getId());
        log.info("有一连接关闭："+interfaceName+session.getId()+"，当前在线人数为："+integer);
    }

    /**
     * 收到客户端消息后调用的方法
     * @param
     */
    @OnMessage
    public void onMessage(@PathParam("interfaceName")String interfaceName,String message, Session session) throws IOException {
        log.info("服务端收到客户端"+interfaceName+session.getId()+"的消息:"+message);
        sendMessageClients.put(interfaceName+session.getId(), session);
        pageAnd.resSet(interfaceName);
        this.sendMessage(interfaceName,null);
    }

    @OnError
    public void onError(@PathParam("interfaceName")String interfaceName,Session session, Throwable error) {
        log.error("连接发生错误");
        clients.remove("连接错误，关闭"+interfaceName+session.getId());
    }

    /**
     * 群发消息
     * @param message
     */
    public void sendMessage(String interfaceName,String message) throws IOException {
        for (Map.Entry<String, Session> sessionEntry : clients.entrySet()) {
            Session toSession = sessionEntry.getValue();
            String keyValue = toSession.getRequestURI().getPath().replace("/ht-datadevelop/webSocket/timing/table/", "");
            if(interfaceName.equalsIgnoreCase(keyValue)){
                synchronized (toSession){
                    if(StringUtils.isNotEmpty(message)){
                        toSession.getBasicRemote().sendText(message);
                        log.info("推送消息结束："+message);
                    }
                }
            }
        }
    }
}
